package com.toman.ui.menu;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.SysMenuEntityNew;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.toman.toolbar.ToolBarWhiteActivity;
import com.toman.ui.menu.adapter.MenuParentAdapter;
import com.toman.ui.menu.adapter.MyAdapter;
import com.ywanhzy.demo.AppConfig;
import com.ywanhzy.demo.AppContext;
import com.ywanhzy.demo.drag.DragCallback;
import com.ywanhzy.demo.drag.DragForScrollView;
import com.ywanhzy.demo.drag.DragGridView;
import com.ywanhzy.demo.entity.MenuEntity;
import com.ywanhzy.demo.ui.DensityUtil;
import com.ywanhzy.demo.widget.CustomExpandableListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

public class MenuManageActivity extends ToolBarWhiteActivity {

    @BindView(R.id.tv_item_cate_name)
    TextView tvItemCateName;
    @BindView(R.id.tv_drag_tip)
    TextView tvDragTip;
    @BindView(R.id.gridview)
    DragGridView dragGridView;
    @BindView(R.id.tab_main)
    TabLayout tab_main;
    @BindView(R.id.expandableListView)
    CustomExpandableListView expandableListView;
    @BindView(R.id.sv_index)
    DragForScrollView sv_index;
    private static AppContext appContext;
    MenuItem menuItem;
    private static MyAdapter adapterSelect; //
    private static List<MenuEntity> indexSelect = new ArrayList<MenuEntity>();
    @BindView(R.id.ll_drag)
    LinearLayout llDrag;
    private ArrayList<Integer> listPosition = new ArrayList<>();
    private static ArrayList<MenuEntity> indexAll = new ArrayList<MenuEntity>();
    private static MenuParentAdapter menuParentAdapter;
    static int maxSelectCount = 11;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_manage_new);
        ButterKnife.bind(this);
        initToolBar("全部应用");
        initData();
        initView();
        getAll();


    }

    private void initData() {
        appContext = (AppContext) getApplication();
        adapterSelect = new MyAdapter(this, appContext, indexSelect);

        try {
            List<MenuEntity> indexDataList = (List<MenuEntity>) appContext.readObject(AppConfig.KEY_USER);
            if (indexDataList != null) {
                indexSelect.clear();
                indexSelect.addAll(indexDataList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            List<MenuEntity> indexAllList = (List<MenuEntity>) appContext.readObject(AppConfig.KEY_All);
            if (indexAllList != null) {
                indexAll.clear();
                indexAll.addAll(indexAllList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        menuItem = menu.findItem(R.id.menu_edit);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            setTvTitle("编辑我的应用");

                            llDrag.setVisibility(View.VISIBLE);
                            adapterSelect.setEdit();
                            if (menuParentAdapter != null) {
                                menuParentAdapter.setEdit();
                            }
                        } else {
                            item.setTitle("编辑");
                            llDrag.setVisibility(View.GONE);
                            setTvTitle("全部应用");

                            adapterSelect.endEdit();
                            if (menuParentAdapter != null) {
                                menuParentAdapter.endEdit();
                            }
                            save();
//                            postMenu();
                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }


    private void initView() {

        dragGridView.setAdapter(adapterSelect);
        dragGridView.setDragCallback(new DragCallback() {
            @Override
            public void startDrag(int position) {
                System.out.println("start drag at " + position);
                sv_index.startDrag(position);
            }

            @Override
            public void endDrag(int position) {
                System.out.println("end drag at " + position);
                sv_index.endDrag(position);
            }
        });
        dragGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("setOnItemClickListener", adapterSelect.getEditStatue() + "");
                if (!adapterSelect.getEditStatue()) {
                    //dragGridView.clicked(position);
                    MenuEntity cateModel = indexSelect.get(position);
                    if (menuItem.getTitle().equals("编辑")) {
                        MenuJump.go(MenuManageActivity.this, cateModel.getTitle());
                    }
                }
            }
        });
        dragGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (menuItem.getTitle().equals("编辑")) {
                    menuItem.setTitle("完成");
                    adapterSelect.setEdit();
                    if (menuParentAdapter != null) {
                        menuParentAdapter.setEdit();
                    }
                }
                dragGridView.startDrag(position);
                return false;
            }
        });
        menuParentAdapter = new MenuParentAdapter(this, indexAll);
        expandableListView.setAdapter(menuParentAdapter);
        expandableListView.setGroupIndicator(null);

        // expandableListView.expandGroup(6); // 在分组列表视图中 展开一组
        // expandableListView.isGroupExpanded(0); //判断此组是否展开

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                MenuEntity cateModel = indexAll.get(groupPosition);

                return true;
            }
        });
        expandableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                if (menuItem.getTitle().toString().equals("编辑")) {
                    MenuEntity cateModel = indexAll.get(arg2);
                    logSave(cateModel.getId());
                    MenuJump.go(MenuManageActivity.this, cateModel.getTitle());

                }
            }
        });

        expandableListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                if (menuItem.getTitle().equals("编辑")) {
                    menuItem.setTitle("完成");
llDrag.setVisibility(View.VISIBLE);
                    setTvTitle("编辑我的应用");

                    adapterSelect.setEdit();
                    menuParentAdapter.setEdit();
                }
                return false;
            }
        });

        for (int i = 0; i < menuParentAdapter.getGroupCount(); i++) {
            expandableListView.expandGroup(i);
        }
        initAll();

    }

    @Override
    public void onPause() {
        super.onPause();
        ;

    }

    protected void postMenu() {
        // TODO Auto-generated method stub
        List<MenuEntity> indexDataList = (List<MenuEntity>) appContext.readObject(AppConfig.KEY_USER_TEMP);
        String key = AppConfig.KEY_USER;
        appContext.saveObject((Serializable) indexDataList, key);

    }

    public static void DelMeun(MenuEntity indexData, int position) {
        if (indexSelect.size() <= 1) {
            ToastUtil.error(MyApplication.getInstance(), "请最少展示1个模块！");

            return;
        }
        // TODO Auto-generated method stub
        for (int i = 0; i < indexAll.size(); i++) {
            for (int k = 0; k < indexAll.get(i).getChilds().size(); k++) {
                if (indexAll.get(i).getChilds().get(k).getTitle().equals(indexData.getTitle())) {
                    indexAll.get(i).getChilds().get(k).setSelect(false);
                }
            }
        }
        if (menuParentAdapter != null) {
            menuParentAdapter.notifyDataSetChanged();
        }
        adapterSelect.notifyDataSetChanged();
    }

    public static void DelMeunParent(MenuEntity indexData, int position) {
        if (indexSelect.size() <= 1) {
            ToastUtil.error(MyApplication.getInstance(), "请最少展示1个模块！");
            return;
        }
        // TODO Auto-generated method stub
        for (int i = 0; i < indexAll.size(); i++) {
            for (int k = 0; k < indexAll.get(i).getChilds().size(); k++) {
                if (indexAll.get(i).getChilds().get(k).getTitle().equals(indexData.getTitle())) {
                    indexAll.get(i).getChilds().get(k).setSelect(false);

                }
            }
        }
        for (int j = 0; j < indexSelect.size(); j++) {
            if (indexSelect.get(j).getTitle().equals(indexData.getTitle())) {
                indexSelect.remove(indexSelect.get(j));
            }
        }

        if (menuParentAdapter != null) {
            menuParentAdapter.notifyDataSetChanged();
        }
        String key = AppConfig.KEY_USER_TEMP;
        appContext.saveObject((Serializable) indexSelect, key);
        adapterSelect.notifyDataSetChanged();
    }

    public static void AddMenu(MenuEntity menuEntity) {
        if (indexSelect.size() >= maxSelectCount) {
            ToastUtil.error(MyApplication.getInstance(), "超过最大数量！");
            return;
        }
        // TODO Auto-generated method stub
        indexSelect.add(menuEntity);
        String key = AppConfig.KEY_USER_TEMP;
        appContext.saveObject((Serializable) indexSelect, key);

        for (int i = 0; i < indexAll.size(); i++) {
            for (int k = 0; k < indexAll.get(i).getChilds().size(); k++) {
                if (indexAll.get(i).getChilds().get(k).getTitle().equals(menuEntity.getTitle())) {
                    indexAll.get(i).getChilds().get(k).setSelect(true);
                }
            }
        }
        menuParentAdapter.notifyDataSetChanged();
        adapterSelect.notifyDataSetChanged();
    }

    public int getViewHeight(int position) {
        int totalHeight = 0;
        for (int i = 0; i < position; i++) {
            int childSize = indexAll.get(i).getChilds().size();

            totalHeight += DensityUtil.dip2px(this, (float) Math.ceil((float) childSize / 4) * 80 + 30);

        }
        System.out.println("滑动距离：" + totalHeight + "位置" + position);
        return totalHeight;
    }

    public void initViewHeight() {
        listPosition.clear();
        for (int i = 0; i < indexAll.size(); i++) {
            int totalHeight = 0;
            for (int j = 0; j < i; j++) {
                int childSize = indexAll.get(j).getChilds().size();

                totalHeight += DensityUtil.dip2px(this, (float) Math.ceil((float) childSize / 4) * 80 + 30);

            }
            listPosition.add(totalHeight);

        }
        Log.d("ok", "当前listPosition的位置——>" + listPosition + ":");

    }

    public int getPosition(int y) {

        for (int i = 0; i < listPosition.size(); i++) {

            if (listPosition.get(i) > y) {

                if (i != 0) {
                    if (y - listPosition.get(i - 1) > listPosition.get(i) - y) {
                        return i;
                    } else {
                        return i - 1;
                    }
                }
            }
        }
        return 0;
    }


    private void initTab() {
        tab_main.removeAllTabs();
        for (MenuEntity entity : indexAll) {
            tab_main.addTab(tab_main.newTab().setText(entity.getTitle()));
        }
        tab_main.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();

                if (tab.getPosition() != -1) {  //切换RecyclerView位置
                    sv_index.smoothScrollTo(0, getViewHeight(position));
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        sv_index.setScrollViewListener(new DragForScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(DragForScrollView scrollView, int x, int y, int oldx, int oldy) {

                Log.d("ok", "当前scrollView的位置——>" + y + ":" + getPosition(y));
                tab_main.setScrollPosition(getPosition(y), 0, true);

            }
        });
    }

    public void getAll() {
        OkHttpUtils
                .get(NewBaseUrl.company_customusermenu_all_List)
                .params("token", token)
                .params("userId", (String) SPUtils.get(getApplicationContext(), "userid", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "选择的项目: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());


                        if (code == 0) {
                            indexAll.clear();
//                            PermissonUtils.clear(getApplicationContext());
                            List<SysMenuEntityNew> menuList = new ArrayList<SysMenuEntityNew>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("sysEmployeeMenuList"), SysMenuEntityNew.class));

                            for (SysMenuEntityNew entityNew : menuList) {

                                MenuEntity menuEntity = new MenuEntity();
                                menuEntity.setTitle(entityNew.getName());
                                menuEntity.setId(entityNew.getMenuId());
                                menuEntity.setChilds(new ArrayList<>());
                                for (SysMenuEntityNew entityChild : entityNew.getList()) {
                                    MenuEntity childEntity = new MenuEntity();
                                    childEntity.setTitle(entityChild.getName());
                                    childEntity.setIco(entityChild.getAppIconUrl());
                                    childEntity.setId(entityChild.getMenuId());
                                    if (StringUtils.isNotEmpty(entityChild.getIsUse())) {
                                        if (entityChild.getIsUse().equals("1")) {
                                            childEntity.setSelect(true);
                                        }
                                    }
                                    try {
//                                        for (SysMenuEntityNew sysMenuEntityPer : entityChild.getList()) {
//                                            PermissonUtils.put(getApplicationContext(), entityChild.getName() + sysMenuEntityPer.getName(), "是");
//                                            ToastUtil.print(entityChild.getName() + sysMenuEntityPer.getName() + ";");
//                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    menuEntity.getChilds().add(childEntity);
                                }

                                indexAll.add(menuEntity);
                            }
                            appContext.saveObject((Serializable) indexAll, AppConfig.KEY_All);

                            menuParentAdapter.notifyDataSetChanged();
                            for (int i = 0; i < menuParentAdapter.getGroupCount(); i++) {
                                expandableListView.expandGroup(i);
                            }
                            initAll();

                        } else {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();
                        }

                    }
                });
    }

    public void save() {
        StringBuilder stringBuilder = new StringBuilder();
        for (MenuEntity menuEntity : indexSelect) {
            if (stringBuilder.length() <= 0) {
                stringBuilder.append(menuEntity.getId());
            } else {
                stringBuilder.append(",").append(menuEntity.getId());
            }
        }
        String customMenuId = stringBuilder.toString();
        if (customMenuId.equals("null")) {
            customMenuId = "";
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("customMenuId", customMenuId);

        OkHttpUtils
                .post(NewBaseUrl.company_customusermenu_update)
                .headers("token", token)
                .postJson(JsonUtils.obj2JsonString(map))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "保存: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());


                        if (code == 0) {
//                            getAll();
                            postMenu();
                            ToastUtil.success(getApplicationContext(), jsonObj.getString("msg"));

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }
    public void logSave(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("menuId",id);
        OkHttpUtils
                .post(NewBaseUrl.log_save)
                .headers("token", (String) SPUtils.get(getApplicationContext(), "token", ""))
                .postJson(JsonUtils.obj2JsonString(map))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {

                    }
                });
    }

    private void initAll() {
        initViewHeight();
        initTab();
    }
}
